import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import { reqSearchDetail } from "@/api/search";
interface initialStateType {
  loading: boolean;
  searchData: any;
  pagination: any;
}
const initialState: initialStateType = {
  loading: true,
  searchData: null,
  pagination: null,
};
export const fetchProductSearch = createAsyncThunk(
  "SearchSlice/fetchProductSearch",
  async (
    paramaters: {
      nextPage: number | string;
      pageSize: number | string;
      keywords?: string;
    },
    thunkAPI,
  ) => {
    const response = await reqSearchDetail(
      paramaters.nextPage,
      paramaters.pageSize,
      paramaters.keywords,
    );
    return {
      data: response.data,
      pagination: response.headers["x-pagination"],
    };
  },
);
export const SearchSlice = createSlice({
  name: "SearchSlice",
  initialState,
  reducers: {},
  extraReducers: {
    [fetchProductSearch.pending.type]: (state) => {
      state.loading = true;
    },
    [fetchProductSearch.fulfilled.type]: (state, action) => {
      state.loading = false;
      state.searchData = JSON.parse(action.payload.data);
      state.pagination = JSON.parse(action.payload.pagination);
    },
  },
});
